/**
 * 
 */
package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * @author 陈剑波
 * 2017-5-14
 */
public class ContextUtils {
	private static final Base64 base64 = new Base64(true);
	public static final String LAST_PAGE = "LAST_PAGE";
    public static final String REDIRECT_HOME = "/";
    public static ModelMap getSharedata(){
		return (ModelMap)getSession().getAttribute("sharedata");
	}
    public static Set<String> getParameterNames() {
    	Set<String> all = new HashSet<String>();
    	Enumeration<String> enu = getRequest().getParameterNames();
    	while(enu.hasMoreElements()){
    		String p = enu.nextElement();
    		if(p.indexOf(".") > 0) all.add(p.substring(0, p.indexOf(".")));
    		all.add(p);
    	}
    	return all;
	}
    //取得上下文路径
    public static String getContextPath() {
		return getRequest().getContextPath();
	}
    //取得request的属性
    public static Object getAttribute(String name) { 
        return getRequest().getAttribute(name);   
    }
    
    //取得完整的请求
    @SuppressWarnings("deprecation")
	public static String getFullServletPath() {
    	HttpServletRequest request = getRequest();
    	String r = request.getServletPath();
    	if(r == null) return "";
    	if(request.getQueryString() == null || request.getQueryString().length() == 0) return r;
    	return r + "?" + URLDecoder.decode(request.getQueryString());
    	//return r + "?" + StringUtil.decodeUnicode(request.getQueryString());
    }
    
    /**  
     * 设置Attribute  
     * @param name - 名称(key)  
     * @param value - 对象(value)  
     */  
    public void setAttribute(String name, Object value) {   
    	getRequest().setAttribute(name, value);   
    }   
    //前端操作返回
	public static JSONObject ret(Boolean success, String message){
		JSONObject o = new JSONObject();
		o.put("success", success);
		o.put("message", message);
		return o;
	}
	//取得访问者的IP地址
	public static String getIpAddr() { 
		HttpServletRequest request = getRequest();
	    String ip = request.getHeader("x-forwarded-for");    
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
	        ip = request.getHeader("Proxy-Client-IP");    
	    }    
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
	        ip = request.getHeader("WL-Proxy-Client-IP");    
	    }    
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
	        ip = request.getRemoteAddr();    
	    }    
	    return ip;    
	}
    /**
     * 获取当前session对象. 若当前线程不是web请求或当前尚未创建{@code session}则返回{@code null}.
     * @return 当前session对象或{@code null}.
     */
	/*
    public static HttpSession getSession() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs == null) {
            return null;
        }
        return attrs.getRequest().getSession(false);
    }
    */
 	public static HttpServletRequest getRequest(){
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	}
 	public static ServletContext getContext(){
		return getSession().getServletContext();
	}
	public static HttpSession getSession(){
		return getRequest().getSession();
	}
    /**
     * 保存当前请求
     */
    public static void saveRequest() {
        HttpServletRequest request = getRequest();
        request.getSession().setAttribute(LAST_PAGE, hashRequestPage(request));
        //L.info(new Throwable().getStackTrace()[0] + "\n" + "save request for {}" + ContextUtil.hashRequestPage(request));
    }
    
    /**
     * 加密请求页面
     * @param request
     * @return
     */
    public static String hashRequestPage(HttpServletRequest request) {
        String reqUri = request.getRequestURI();
        String query = request.getQueryString();
        if (query != null) {
            reqUri += "?" + query;
        }
        String targetPage = null;
        try {
            targetPage = base64.encodeAsString(reqUri.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            //this does not happen
        }
        return targetPage;
    }
    
    /**
     * 取出之前保存的请求
     * @return
     */
    public static String retrieveSavedRequest() {
        HttpSession session = getSession();
        if (session == null) {
            return REDIRECT_HOME;
        }
        String HashedlastPage = (String) session.getAttribute(LAST_PAGE);
        if (HashedlastPage == null) {
        	return REDIRECT_HOME;
        } else {
            return retrieve(HashedlastPage);
        }
    }
    //把前端取得的所有参数放到一个HashMap中
    public static Map<String, Object> getParameters() {
    	HttpServletRequest req = getRequest();
		Map<String, Object> map = new HashMap<String, Object>();
    	Enumeration<String> enu = req.getParameterNames(); 
    	while(enu.hasMoreElements()) {
    		 String name = enu.nextElement();
    		 if(name.indexOf("*") == 0){
    			 map.put(name, req.getParameterValues(name));
    			 /*
    			 String[] arr = req.getParameterValues(name);
    			 if(arr.length > 0){
    				 System.out.println("个数：" + arr.length);
    				 for(String s: arr){
    					 System.out.println(name + " = " + s);
    				 }
    			 }
    			 */
    		 }else {
				map.put(name, req.getParameter(name));
    		 }
    	}
		return map;
	}
    public static Map<String, Object> getParams(){
    	return getParameters();
    }
    public static String toQueryString() {
		String r = "";
		Map<String, Object> map = getParameters();
		if(map == null) return r;
		r += map.get("action") + ".action?rand=" + Math.random();
		for(String key: map.keySet()) {
			if(!key.equals("action")) r += "&" + key + "=" + map.get(key);
		}
		return r;
	}
    
    public static String[] getParameterValues(String name){
    	return getRequest().getParameterValues(name);
    }
    public static JSONObject getParametersJson(){
    	JSONObject o = new JSONObject();
    	o.putAll(getParameters());
    	return o;
    }
    public static String getParameter(String name) {
		return getRequest().getParameter(name);
	}
    /**
     * 解密请求的页面
     * @param targetPage
     * @return
     */
    public static String retrieve(String targetPage) {
        byte[] decode = base64.decode(targetPage);
        try {
            String requestUri = new String(decode, "UTF-8");
            int i = requestUri.indexOf("/", 1);
            return requestUri.substring(i);
        } catch (UnsupportedEncodingException ex) {
            //this does not happen
            return null;
        }
    }

}

























































